from flask import Blueprint, jsonify, request, json
from R_CMgmt.riskCopeOperation import copeRecordOprt

riskCopeRecord = Blueprint('riskCopeRecord', __name__)


@riskCopeRecord.route('/copeRecordIndex', methods=['GET'])
def copeRecordIndex():
    return "1"


@riskCopeRecord.route('/init', methods=['GET'])
def init():
    json_str = copeRecordOprt.getAllCopeRecord()
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeRecord.route('/addRiskCope', methods=['POST'])
def addRiskCope():
    print("new a RiskCope")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if copeRecordOprt.addRiskCopeToDB(json_data.get('risk_id')):
        return jsonify(1)
    else:
        return jsonify(2)


@riskCopeRecord.route('/getRiskForCope', methods=['GET'])
def getRiskForCope():
    json_str = copeRecordOprt.getRiskForCopeFromDB()
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeRecord.route('/select', methods=['POST'])
def copeRecordVagueSelect():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    word = json_data.get('word')

    json_str = copeRecordOprt.searchCopeRecord(word)
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeRecord.route('/delete', methods=['POST'])
def deleteCopeRecord():
    data = request.get_data()
    print(data)
    word = data.decode("utf-8")
    print(word)

    if copeRecordOprt.deleteCopeRecordFromDB(word):
        return jsonify(1)
    else:
        return jsonify(2)


@riskCopeRecord.route('/getCopeWithCopeID', methods=['POST'])
def getCopeWithCopeID():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    risk_cope_id = json_data.get('risk_cope_id')

    json_str = copeRecordOprt.getCopeWithCopeIDFromDB(risk_cope_id)
    if json_str == 0:
        return json_str

    return jsonify(json_str)
